package ph.com.gs3.formalistics.service.services;

import ph.com.gs3.formalistics.global.utilities.services.ServiceEventNotifierUtility;
import ph.com.gs3.formalistics.service.managers.SessionManager;
import ph.com.gs3.formalistics.service.managers.SessionManager.LoginResult;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;

public class AuthenticationService extends IntentService {

	public static final String TAG = AuthenticationService.class.getSimpleName();

	public static final String NAME = AuthenticationService.class.getName();

	public static final String ACTION_ON_LOGIN_SERVICE_DONE = NAME + "_on_login_done";

	public static final String EXTRA_SERVER = "server";
	public static final String EXTRA_EMAIL = "email";
	public static final String EXTRA_PASSWORD = "password";

	public static final String EXTRA_LOGIN_RESULTS = "login_results";

	public AuthenticationService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		// display notification
		ServiceEventNotifierUtility.getDefaultInstance().displayBasicNotification(this,
		        "Authenticating");

		// initialize parameters
		Bundle extras = intent.getExtras();

		String server = extras.getString(EXTRA_SERVER);
		String email = extras.getString(EXTRA_EMAIL);
		String password = extras.getString(EXTRA_PASSWORD);

		// login
		SessionManager sessionMan = SessionManager.getApplicationInstance();
		LoginResult loginResult = sessionMan.login(server, email, password);

		// dismiss notification
		ServiceEventNotifierUtility.getDefaultInstance().dismissPrimaryNotification(this);

		broadcastResults(loginResult);

	}

	private void broadcastResults(LoginResult result) {

		Intent broadcastIntent = new Intent();
		broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);

		broadcastIntent.setAction(ACTION_ON_LOGIN_SERVICE_DONE);
		broadcastIntent.putExtra(EXTRA_LOGIN_RESULTS, result);

		sendBroadcast(broadcastIntent);

		stopSelf();

	}

}
